<template>
  <div>
    <div
      class="contract"
      v-if="!contractAddShow && !paymentCollectionShow && !contractDtlShow"
    >
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-if="route.name === 'Contract'"
          v-hasPermi="['system:contractManage:query']"
          class="btn search"
          @click="getContractList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-if="route.name === 'ContractCheck'"
          v-hasPermi="['system:contractCheck:query']"
          class="btn search"
          @click="getContractList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-hasPermi="['system:contractManage:add']"
          v-if="route.name === 'Contract'"
          class="btn search"
          @click="
            contractAddShow = true;
            pageType = 'add';
          "
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
        <el-button
          class="btn save"
          @click="handleExport()"
          ><el-icon class="icon" color="#fff"> <Download /> </el-icon
          >导出列表</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="contractCode">合同编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="contractName">合同名称</el-checkbox>
            </div>
            <div>
              <el-checkbox label="contractKindName">合同类型</el-checkbox>
            </div>
            <div>
              <el-checkbox label="salesmanName">业务人员</el-checkbox>
            </div>
            <div>
              <el-checkbox label="contractMoney">合同金额（万）</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectNames">关联项目</el-checkbox>
            </div>
           
            <div>
              <el-checkbox label="checkStatusName">审核状态</el-checkbox>
            </div>
            <!-- <div>
              <el-checkbox label="nextNodeName">下步流程</el-checkbox>
            </div> -->
            <!-- <div>
              <el-checkbox label="contractCategoryName">项目种类</el-checkbox>
            </div>
            <div>
              <el-checkbox label="contractTypeName">项目类型</el-checkbox>
            </div>
            <div>
              <el-checkbox label="implementationName">是否已实施</el-checkbox>
            </div> -->
            <!-- <div>
              <el-checkbox label="deptName">创建部门</el-checkbox>
            </div> -->
            <div>
              <el-checkbox label="createUserName">创建人员</el-checkbox>
            </div>
           
            <div>
              <el-checkbox label="createTime">创建时间</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.contractCode"
            class="search-input"
            maxlength="30"
            placeholder="请输入合同编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.contractName"
            class="search-input"
            maxlength="30"
            placeholder="请输入合同名称"
          ></el-input>
        </div>
       
        <div class="search-item">
          <el-select
            v-model="params.contractKind"
            placeholder="请选择合同类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in contractKindList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>

        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.contractCode"
            class="search-input"
            maxlength="30"
            placeholder="请输入业务人员"
          ></el-input>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.userName"
            placeholder="请选择审核状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in checkListOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.projectName"
            class="search-input"
            maxlength="30"
            placeholder="请输入关联项目"
          ></el-input>
        </div>
        <!-- <div class="search-item">
          <el-select
            v-model="params.contractCategory"
            placeholder="请选择项目种类"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in kindList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.contractType"
            placeholder="请选择项目类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in typeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.implementation"
            placeholder="请选择是否已实施"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in impleList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div> -->
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="contractList"
        border
        height="64vh"
        :header-cell-style="{ 'text-align': 'center' }"
        @sort-change="sortChange"
      >
        <!-- 操作模式 -->
        <el-table-column
          label="操作"
          :show-overflow-tooltip="true"
          width="180px"
        >
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                v-if="
                  route.name === 'Contract' &&
                  [0, 5, 6].includes(row.checkStatus)
                "
                v-hasPermi="['system:contractManage:edit']"
                title="编辑"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
              >
                <Edit />
              </el-icon>
              <el-icon
                v-if="route.name === 'Contract'"
                v-hasPermi="['system:contractManage:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-if="route.name === 'ContractCheck'"
                v-hasPermi="['system:contractCheck:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'Contract' && [1].includes(row.checkStatus)
                "
                v-hasPermi="['system:contractManage:revoke']"
                title="撤销"
                color="#BBBBBB"
                class="table-icon"
                :size="20"
                @click="handleOperate('revoke', row)"
              >
                <img
                  src="@/assets/icons/images/repeal.png"
                  style="width: 18px; height: 18px"
                />
              </el-icon>
              <!-- route.name === 'ContractCheck' && -->
              <el-icon
                v-if="[1, 2].includes(row.checkStatus) && row.auditStatus == 1"
                v-hasPermi="['system:contract:check']"
                title="审核"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('check', row)"
              >
                <Checked />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'Contract' &&
                  row.checkStatus == 3 &&
                  row.contractKind != 2
                "
                v-hasPermi="['system:contractManage:paymentCollection']"
                title="回款"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('paymentCollection', row)"
              >
                <Money />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'Contract' && [0, 5].includes(row.checkStatus)
                "
                v-hasPermi="['system:contractManage:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'ContractCheck' &&
                  [0, 5].includes(row.checkStatus) &&
                  false
                "
                v-hasPermi="['system:contractCheck:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="70"
          align="center"
        />
        <el-table-column
          label="合同编号"
          prop="contractCode"
          v-if="checkList.includes('contractCode')"
          :show-overflow-tooltip="true"
          width="200"
          sortable="custom"
        />
        <el-table-column
          label="合同名称"
          prop="contractName"
          v-if="checkList.includes('contractName')"
          :show-overflow-tooltip="true"
          min-width="200"
          sortable="custom"
        />
        <el-table-column
          label="合同类型"
          prop="contractKindName"
          v-if="checkList.includes('contractKindName')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="业务人员"
          prop="salesmanName"
          v-if="checkList.includes('salesmanName')"
          :show-overflow-tooltip="true"
          width="130"
          sortable="custom"
        />
        <el-table-column
          label="审核状态"
          prop="checkStatusName"
          v-if="checkList.includes('checkStatusName')"
          :show-overflow-tooltip="true"
          width="130"
          sortable="custom"
        >
          <template #default="{ row }">
            <span :style="getStatusColor(row.checkStatusName)">{{
              row.checkStatusName
            }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="合同金额（万）"
          prop="contractMoney"
          v-if="checkList.includes('contractMoney')"
          :show-overflow-tooltip="true"
          width="150"
          sortable="custom"
        />
        <!-- <el-table-column
          label="已收金额（万）"
          prop="acceptMoney"
          v-if="checkList.includes('acceptMoney')"
          :show-overflow-tooltip="true"
          width="160"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>{{ row.acceptMoney ? row.acceptMoney : "--" }}</span>
          </template>
        </el-table-column> -->
        <el-table-column
          label="关联项目"
          prop="projectNames"
          v-if="checkList.includes('projectNames')"
          :show-overflow-tooltip="true"
          width="130"
          sortable="custom"
        />
        <el-table-column
          label="创建人员"
          prop="createUserName"
          v-if="checkList.includes('createUserName')"
          :show-overflow-tooltip="true"
          width="130"
          sortable="custom"
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          v-if="checkList.includes('createTime')"
          :show-overflow-tooltip="true"
          width="160"
          sortable="custom"
        />
       
        
        <!-- <el-table-column
          label="下步流程"
          prop="nextNodeName"
          v-if="checkList.includes('nextNodeName')"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />
        <el-table-column
          label="项目种类"
          prop="contractCategoryName"
          v-if="checkList.includes('contractCategoryName')"
          :show-overflow-tooltip="true"
          width="130"
          sortable="custom"
        />
        <el-table-column
          label="项目类型"
          prop="contractTypeName"
          v-if="checkList.includes('contractTypeName')"
          :show-overflow-tooltip="true"
          width="130"
          sortable="custom"
        />
        <el-table-column
          label="是否已实施"
          prop="implementationName"
          v-if="checkList.includes('implementationName')"
          :show-overflow-tooltip="true"
          width="150"
          sortable="custom"
        />
        <el-table-column
          label="创建部门"
          prop="deptName"
          v-if="checkList.includes('deptName')"
          :show-overflow-tooltip="true"
          width="130"
          sortable="custom"
        /> -->
      
      
       
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getContractList"
      />
    </div>
    <ContractAdd
      ref="contractAddRef"
      v-if="contractAddShow"
      v-model:contractAddShow="contractAddShow"
      @refreshList="getContractList"
      :pageType="pageType"
    />

    <ContractDtl
      ref="contractDtlRef"
      v-else
      v-if="contractDtlShow"
      v-model:contractDtlShow="contractDtlShow"
      @refreshList="getContractList"
      :pageType="pageType"
    />
    <PaymentCollection
      ref="paymentCollectionRef"
      v-if="paymentCollectionShow"
      v-model:contractAddShow="paymentCollectionShow"
      @refreshList="getContractList"
      :pageType="pageType"
    />
  </div>
</template>

<script setup>
import { ref, provide, inject, onMounted, defineProps } from "vue";
const { proxy } = getCurrentInstance();
import ContractAdd from "./contractAdd.vue";
import ContractDtl from "./dtl.vue";
import PaymentCollection from "./paymentCollection.vue";
import {
  getContractListApi,
  getContractCheckListApi,
  deleteContractApi,
  cancelContract,
} from "@/api/sales/contract";
import { getDictsApi } from "@/api/dict";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
// 路由
const route = useRoute();
//当前用户信息
const userStore = useUserStore();
// 搜索参数
const params = reactive({
  checkStatus: null, // 合同审核状态
  contractCategory: null, // 项目种类
  contractKind: null, // 合同种类
  contractCode: "", // 合同编号
  projectName: "", // 关联项目
  contractName: "", // 合同名称
  userName: "", // 业务人员
  contractType: null, // 项目类型
  implementation: null, // 是否已实施
  pageNum: 1,
  pageSize: 50,
  sortField: "",
  sortOrder: "",
});

const checkList = ref([
  "contractCode",
  "contractName",
  "contractMoney",
  "projectNames",
  "acceptMoney",
  "contractKindName",
  "checkStatusName",
  "nextNodeName",
  "contractCategoryName",
  "contractTypeName",
  "implementationName",
  "deptName",
  "createUserName",
  "salesmanName",
  "createTime",
]);

// 表格加载效果
const loading = ref(false);
// 合同新增组件显隐
const contractAddShow = ref(false);
// 回款新增组件显隐
const paymentCollectionShow = ref(false);
// 合同列表
const contractList = ref([]);
// 总数
const total = ref(0);
// 合同新增组件引用
const contractAddRef = ref(null);

const contractDtlShow = ref(false);
const contractDtlRef = ref(null);

// 回款组件引用
const paymentCollectionRef = ref(null);
// 操作类型
const pageType = ref("");
// 审核状态列表
const checkListOptions = ref([]);
// 项目种类列表
const kindList = ref([]);
// 合同种类列表
const contractKindList = ref([]);
// 是否实施
const impleList = ref([]);
// 合同类型列表
const typeList = ref([]);

/**
 * @description: 复选框选中
 */
const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType: route.name === "Contract" ? 10 : 11,
    titleField: str,
  });
};

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: route.name === "Contract" ? 10 : 11,
  });
  console.log('获取表头')
  console.log(result)
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getContractList();
};

/**
 * @description: 处理导出
 * @param {String} flag 1.列表 2.明细列表
 */
 const handleExport = async () => {
  // 日期
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  let month = currentDate.getMonth() + 1; // 月份是从 0 开始计数的，因此要加1
  if (month < 10) {
    month = "0" + month;
  }
  const day = currentDate.getDate();
  let date = year + "" + month + "" + day;
  // 随机数
  let randomNum = Math.floor(Math.random() * (999 - 100 + 1) + 100);
  // 用户昵称
  let userName = userStore.name;
  // 文件名
  let fileNmae = date + userName + randomNum;
  let { pageNum, pageSize } = params;
   params.fields = checkList.value
    /* 导出列表 */
    proxy.download(
      `/system/contract/export?pageNum=${pageNum}&pageSize=${pageSize}`,
      params,
      `${fileNmae}.xlsx`,
      null,
      1
    );
};

/**
 * @description: 重置
 */
const handleRefresh = () => {
  Object.assign(params, {
    checkStatus: null, // 合同审核状态
    contractCategory: null, // 合同种类
    contractCode: "", // 合同编号
    projectName: "", // 关联项目
    contractName: "", // 合同名称
    userName: "", // 业务人员
    contractType: null, // 合同类型
    implementation: null, // 是否已实施
    pageNum: 1,
    pageSize: 50,
    sortField: "",
    sortOrder: "",
  });
  getContractList();
};

/**
 * @description: 获取合同列表
 */
const getContractList = async () => {
  try {
    loading.value = true;
    // if (route.name === "Contract") {
    //   params.auditType = 1;
    // } else {
    // }
    params.auditType = 2;
    let { pageNum, pageSize } = params;
    let res;
    // if (route.name === "Contract") {
    //   res = await getContractListApi({ pageNum, pageSize }, params);
    // } else {
    // }
   
    res = await getContractCheckListApi({ pageNum, pageSize }, params);

    contractList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};
provide("getNonContractual", getContractList);

/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "edit":
      pageType.value = type;
      contractAddShow.value = true;
      nextTick(() => {
        contractAddRef.value.handleDetailInfo(row.contractId);
      });
      break;
    case "detail":
      pageType.value = type;
      contractDtlShow.value = true;
      nextTick(() => {
        contractDtlRef.value.handleDetailInfo(row.contractId);
      });
      break;
    case "revoke":
      ElMessageBox.confirm("此操作将撤销该合同管理信息，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          let param = {
            contractId: row.contractId,
            checkStatus: 5,
            contractKind: row.contractKind,
            renew: row.renew,
          };
          const res = await cancelContract(param);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getContractList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;
    case "check":
      pageType.value = type;
      contractAddShow.value = true;
      nextTick(() => {
        contractAddRef.value.handleDetailInfo(row.contractId, row.contractKind);
      });
      break;
    case "paymentCollection":
      paymentCollectionShow.value = true;
      nextTick(() => {
        paymentCollectionRef.value.handleDetailInfo(row.contractId);
      });
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该合同，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteContractApi(row.contractId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getContractList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("erp_contract_check_status").then((res) => {
    // 审核状态
    if (res.code === 200) {
      checkListOptions.value = res.data;
    }
  });

  await getDictsApi("erp_warehousing").then((res) => {
    // 是否实施
    if (res.code === 200) {
      impleList.value = res.data;
    }
  });

  await getDictsApi("erp_contract_kind").then((res) => {
    // 合同种类
    if (res.code === 200) {
      contractKindList.value = res.data;
    }
  });
  await getDictsApi("erp_contract_category").then((res) => {
    // 项目种类
    if (res.code === 200) {
      kindList.value = res.data;
    }
  });
  await getDictsApi("erp_contract_type").then((res) => {
    // 项目类型
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });
}

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

onMounted(() => {
  getTableHeader();
  // 路由携带项目id参数，直接显示详情页
  if (route.query?.contractId) {
    let contractId = route.query.contractId;
    pageType.value = "detail";
    contractDtlShow.value = true;
    nextTick(() => {
      contractDtlRef.value.handleDetailInfo(contractId);
    });
  }
  getDicts();
  getContractList();

  if (route.query?.businessId) {
    let applyId = route.query.businessId;
    if (
      route.query.checkStatus === "待审核" ||
      route.query.checkStatus === "审核中"
    ) {
      pageType.value = "check";
      contractAddShow.value = true;
      nextTick(() => {
        contractAddRef.value.handleDetailInfo(Number(applyId));
      });
    }
  }
  if (route.query?.myinfoId) {
    let applyId = route.query.myinfoId;
    pageType.value = "detail";
    contractAddShow.value = true;
    nextTick(() => {
      contractAddRef.value.handleDetailInfo(Number(applyId));
    });
  }
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.contract {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
}
</style>
